package com.learning.spring.ioc.bean.xml.injection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * ClassName: InjectionType
 * Description: 依赖注入的方式
 * 1、构造函数注入
 * 2、属性注入：需要属性的setter 与getter 方法
 * Date: 2018/7/26 9:55 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class InjectionMethod {

    public static void main(String[] args) {
//        test();
        whileDependency();
    }


    /**
     * 依赖注入的两种方式:
     * BeanInjectionService 依赖 FieldInjection、ConstructorInjection
     * FieldInjection - 属性方式注入, <property>
     * ConstructorInjection - 构造函数方式注入, <constructor-arg>
     */
    public static void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
        BeanInjectionService beanInjectionService = context.getBean("beanInjectionService", BeanInjectionService.class);

        beanInjectionService.get();
        beanInjectionService.done();

        /*
         调用 FieldInjection.get() 方法
         调用 ConstructorInjection.done() 方法
        */
    }

    /**
     * 构造函数实现注入，循环依赖问题：
     * Sam 与 Eason 相互依赖，导致 ApplicationContext 启动失败
     * 解决：构造函数注入改成 属性注入就可以了
     */
    public static void whileDependency() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");

        Sam sam = context.getBean("sam", Sam.class);
        Eason eason = context.getBean("eason", Eason.class);
    }
}

class Sam {
    private Eason eason;

    public Sam(Eason eason) {
        this.eason = eason;
    }
}

class Eason {
    private Sam sam;

    public Eason(Sam sam) {
        this.sam = sam;
    }
}
